package com.jason.apps.dashboard;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.HashMap;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.R;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.alert.EmptyAlert;
import com.jason.apps.alert.ErrorAlert;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

@SuppressLint("ParserError")
public class PersonDetail extends SherlockFragment implements OnDateSetListener {
	
	public EditText fname;
	public EditText lname;
	public EditText email;
	public EditText mobile;
	public EditText landline;
	public EditText bday;
	public EditText username;
	public EditText password;
	public EditText filepath;
	public Button edit;
	public Button browse;
	public Spinner type;
	public ImageButton cal;
	
	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image";
	
	static int id;
	
	final static String ARG_POSITION = "position";
    int mCurrentPosition = -1;
	
	FTPClient con = null;
	
	SherlockFragmentActivity fa;
	ConsumeWebService consume=new ConsumeWebService();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }
		
		View view=inflater.inflate(R.layout.edit, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();

		 fname=(EditText)view.findViewById(R.id.editfname);
		 lname=(EditText)view.findViewById(R.id.editlname);
		 email=(EditText)view.findViewById(R.id.editemail);
		 mobile=(EditText)view.findViewById(R.id.editmobile);
		 landline=(EditText)view.findViewById(R.id.editlandLine);
		 bday=(EditText)view.findViewById(R.id.editbday);
		 username=(EditText)view.findViewById(R.id.editusername);
		 password=(EditText)view.findViewById(R.id.editpassword);
		 filepath=(EditText)view.findViewById(R.id.editfilepath);
		 edit=(Button)view.findViewById(R.id.btnEdit);
		 type=(Spinner)view.findViewById(R.id.editspinner);
		 cal=(ImageButton)view.findViewById(R.id.editcalendar);
				 
		 cal.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				 FragmentTransaction ft = getFragmentManager().beginTransaction();
	                SherlockDialogFragment newFragment = new DatePickerDialogFragment(
	                        PersonDetail.this);
	                newFragment.show(ft, "Set Date");
			}
		});

		 edit.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if((!fname.getText().toString().trim().equals(""))&&(!lname.getText().toString().trim().equals(""))&&(!email.getText().toString().trim().equals(""))&&(!username.getText().toString().trim().equals(""))&&(!password.getText().toString().trim().equals(""))){
					new Edit().execute();
					}
					else{
						FragmentManager fm = getActivity().getSupportFragmentManager();
					     EmptyAlert alert = new EmptyAlert();
					     alert.show(fm, "Alert_Dialog");
					}
			}
		});
	
		
		return view;
    }
	@Override
    public void onStart() {
        super.onStart();

        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // Set article based on argument passed in
            updateView(args.getInt(ARG_POSITION));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateView(mCurrentPosition);
        }
    }
	
	public void setUrl(String file){
		filepath.setText(file);
	}
	
	public void updateView(int position){
		
		HashMap<String, String> map = EditAccount.mylist.get(position);
    	
		String firstname=map.get("fname");
    	String lastname=map.get("lname");
    	String mob=map.get("mob");
    	String land=map.get("land");
    	String emailadd=map.get("emailAddress");
    	String user=map.get("username");
    	String pass=map.get("password");
    	String Etype=map.get("type");
    	String birthday=map.get("birthday");
    	id=Integer.parseInt(map.get("person_id"));
    	
    	int pos=0;
    	if(Etype.equals("Agent")){
    		pos=0;
    	}
    	else{
    		pos=1;
    	}
    	
    	fname.setText(firstname);
		lname.setText(lastname);
		email.setText(emailadd);
		mobile.setText(mob);
		landline.setText(land);
		bday.setText(birthday);
		username.setText(user);
		password.setText(pass);
		type.setSelection(pos);
    	mCurrentPosition = position;
	}
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }
	
	private void setDateEditText(int year, int month, int day) {
	        bday.setText(year+"-"+month+"-"+day);
	    }
	//DialogFragment
	public class DatePickerDialogFragment extends SherlockDialogFragment {
        private OnDateSetListener mFragment;

        public DatePickerDialogFragment(OnDateSetListener callback) {
            mFragment = callback;
        }

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int cmonth = c.get(Calendar.MONTH);
            int cday = c.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), mFragment, year, cmonth, cday);
        }
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        setDateEditText(year,month+1,day);
    }


	//Asynctask
	public class Edit extends AsyncTask<Void, Void, Void> {

	    private final ProgressDialog dialog = new ProgressDialog(fa);
	    boolean resulta;

	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {

	    	String firstname=fname.getText().toString();
	    	String lastname=lname.getText().toString();
	    	String emailAddress=email.getText().toString();
	    	String mob=mobile.getText().toString();
	    	String land=landline.getText().toString();
	    	String birthday=bday.getText().toString();
	    	String user=username.getText().toString();
	    	String pass=password.getText().toString();
	    	String gettype=type.getSelectedItem().toString();
	    	
	    	String file=filepath.getText().toString().trim();
	    	String filename=new File(file).getName();;
	    	con = new FTPClient();
			try {
				
				
				if(firstname!=null && lastname!=null && emailAddress!=null && user!=null && pass!=null && birthday!=null){
					
					resulta=consume.updatePerson(firstname, lastname, user, pass, emailAddress, mob, land, birthday, gettype, "http://"+host+folderLocation+"/"+filename,id);
					if(resulta){
						con.connect(host);
						
					if((filename!="")){
						Log.v("choya", "nesud"+filename);
						
						if (con.login(ftpuser, ftppass)) {
					
							con.enterLocalPassiveMode(); // important!
							con.setFileType(FTP.BINARY_FILE_TYPE);

							BufferedInputStream buffIn = null;
							buffIn = new BufferedInputStream(
							new FileInputStream(new File(file)));

							boolean result = con.storeFile(saveLocation
							+ folderLocation + filename, buffIn);
							buffIn.close();
							if (result)
								Log.v("upload result", "succeeded");
							con.logout();
							con.disconnect();
							
							
						}
					}
					else{
						resulta=consume.updatePerson(firstname, lastname, user, pass, emailAddress, mob, land, birthday, gettype, "",id);
					
					}
						 
					}
					
					
				}
				
			} catch (Exception e) {
				Log.e("","",e);
			}
	   
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
	    	if(resulta){
	    		FragmentManager fm = getActivity().getSupportFragmentManager();
	             AlertDialogFragment alert = new AlertDialogFragment();
	             alert.show(fm, "Alert_Dialog");
	             clearFields();
	             fm.popBackStack();
	    	}
	    	else{
	    		 FragmentManager fm = getActivity().getSupportFragmentManager();
			     ErrorAlert alert = new ErrorAlert();
			     alert.show(fm, "Alert_Dialog");
	    	}
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }
	 public void clearFields(){
	    	fname.setText("");
	    	lname.setText("");
	    	email.setText("");
	    	mobile.setText("");
	    	landline.setText("");
	    	username.setText("");
	    	password.setText("");
	    	filepath.setText("");
	    	username.setText("");
	    	password.setText("");
	    }

}



   
